package com.iflytek.cosmo.ocr.common.util;

import com.iflytek.cosmo.ocr.model.entity.OcrFileEntity;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;


/**
 * 按文件名称排序工具类
 */
@Slf4j
public class ContUtil {
    public static void fileNameSort(List<OcrFileEntity> fileInfo){
        Collections.sort(fileInfo, new Comparator<OcrFileEntity>() {
            private final Comparator<String> NATURAL_SORT = new FileNameComparator();
            @Override
            public int compare(OcrFileEntity ofe1, OcrFileEntity ofe2) {
                String o1 = ofe1.getFileName();
                String o2 = ofe2.getFileName();
                return NATURAL_SORT.compare(o1, o2);
            }
        });
    }

    public static String genPinYin(String input) {
        if (input == null || input.trim().equals("")) {
            return "";
        }
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);//拼音转小写
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//没有声调
        format.setVCharType(HanyuPinyinVCharType.WITH_V);//
        //多音字预先转换 这里可以处理一下多音字
        char[] chars =  input.trim().toCharArray();
        StringBuilder output = new StringBuilder();
        try {
            for (char c : chars) {
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    if ("嗯".equals(Character.toString(c))){
                        output.append("en");
                    }else {
                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);
                        output.append(temp[0]);
                    }
                } else {
                    output.append(Character.toString(c));
                }
            }
        } catch (Exception e) {
            System.err.println("拼音转换出现未知异常：" + input);
        }
        //System.out.println(output.toString());
        return output.toString();
    }

    public static String upCase2low(String str){
        char[] chars = str.toCharArray();
        StringBuilder newStr = new StringBuilder();
        for(int i = 0; i <chars.length; i++){
            if (Character.toString(chars[i]).matches("[A-Z]")){
                newStr.append(Character.toString(chars[i]).toLowerCase());
            }else {
                newStr.append(Character.toString(chars[i]));
            }
        }
        return newStr.toString();
    }
}